//
//  TanMapVC.m
//  Tan_Map
//
//  Created by 亲哥哥 on 2018/4/29.
//  Copyright © 2018年 亲哥哥. All rights reserved.
//
/*
 要实现的功能：
 1、定位到当前，获取当前位置的经纬度，和地址信息
 2、poi搜索当前和关键字匹配的附近地址位置
 3、点击搜索出的某个地址可以马上定位到那里去
 4、根据经纬度获取地址信息，根据地址信息获取经纬度
 */

#import "TanMapVC.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

@interface TanMapVC ()<BMKMapViewDelegate,BMKLocationServiceDelegate, BMKPoiSearchDelegate, BMKGeoCodeSearchDelegate,UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) BMKMapView *mapView;             //展示地图
@property (nonatomic, strong) BMKLocationService *locService; //用来定位地址信息
@property (nonatomic, strong) BMKPoiSearch *poiSearch;        //用来进行poi关键字地址搜索
//用来进行地理编码和反编码：根据经纬度获取地址，根据地址获取经纬度
@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;

//用来进行poi关键字搜索
@property (nonatomic, strong) UITextField *txtField;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UILabel *addressLbl;

@end

@implementation TanMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initSubControls];
    
    //定位设置
    CGSize size = [UIScreen mainScreen].bounds.size;
    self.mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(10, 120, size.width-20, 400)];
    self.mapView.mapType = BMKMapTypeStandard; //标准地图
    self.mapView.zoomLevel = 14;
    self.mapView.delegate = self;
    self.mapView.layer.borderColor = [UIColor redColor].CGColor;
    self.mapView.layer.borderWidth = 1;
    self.mapView.layer.masksToBounds = YES;
    self.mapView.layer.cornerRadius = 4;
    [self.view addSubview:self.mapView];
    
    self.locService = [BMKLocationService new];
    self.locService.delegate = self;
    
    //开始定位
    [self.locService startUserLocationService];
    self.mapView.showsUserLocation = NO;//先关闭显示的定位图层
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    self.mapView.showsUserLocation = YES;//显示定位图层
    
    //设置poi关键字搜索
    self.poiSearch = [BMKPoiSearch new];
    self.poiSearch.delegate = self;
    
    //设置地理编码和反编码
    self.geoCodeSearch = [BMKGeoCodeSearch new];
    self.geoCodeSearch.delegate = self;
}

#pragma mark implement BMKMapViewDelegate

/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}

#pragma mark - BMKLocationServiceDelegate
/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
    
    NSLog(@"...新用户位置信息：%@, %@", userLocation.title, userLocation.subtitle);
    
    [self.mapView updateLocationData:userLocation];
    [self.locService stopUserLocationService];
    [self getCurrentAddressWithcoordinate: userLocation.location.coordinate];
}

#pragma mark - BMKPoiSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        [self.dataArr removeAllObjects];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
            
            NSLog(@"i: %d, name: %@, 经度： %f, 纬度： %f", i, poi.name, item.coordinate.latitude, item.coordinate.longitude);
            [self.dataArr addObject:poi];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
        
        if (self.dataArr.count > 0){
            self.tableView.hidden = NO;
            [self.view bringSubviewToFront:self.tableView];
            [self.tableView reloadData];
        }
    }
}

#pragma mark - BMKGeoCodeSearchDelegate
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
    
        NSLog(@"正向地理编码: 纬度:%f,经度:%f", item.coordinate.latitude,item.coordinate.longitude);
        self.addressLbl.text = result.address;
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        
        NSLog(@"反向地理编码：%@", item.title);
        self.addressLbl.text = result.address;
    }
}

#pragma mark - private methods
- (void)startSearch{
    
    [self.txtField resignFirstResponder];
    NSString *keyWords = self.txtField.text;
    
    NSLog(@"%@", keyWords);
    
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
    citySearchOption.pageIndex = 0;
    citySearchOption.pageCapacity = 50;
    citySearchOption.city= @"";//_cityText.text;
    citySearchOption.keyword = keyWords;
    BOOL flag = [self.poiSearch poiSearchInCity:citySearchOption];
    NSLog(@"%d", flag);
}

//位置变化后，获取经纬度和地址
- (void)getCurrentAddressWithcoordinate:(CLLocationCoordinate2D)coor{
    
    BMKReverseGeoCodeOption *reverseGeocodeOption = [BMKReverseGeoCodeOption new];
    reverseGeocodeOption.reverseGeoPoint = coor;
    [self.geoCodeSearch reverseGeoCode:reverseGeocodeOption]; //反向编码
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    
    BMKPoiInfo *obj = self.dataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@, %@, %@, %@, %@", obj.name, obj.city, obj.address, obj.phone, obj.postcode];
    /*
     ///POI名称
     @property (nonatomic, strong) NSString* name;
     ///POIuid
     @property (nonatomic, strong) NSString* uid;
     ///POI地址
     @property (nonatomic, strong) NSString* address;
     ///POI所在城市
     @property (nonatomic, strong) NSString* city;
     ///POI电话号码
     @property (nonatomic, strong) NSString* phone;
     ///POI邮编
     @property (nonatomic, strong) NSString* postcode;
     ///POI类型，0:普通点 1:公交站 2:公交线路 3:地铁站 4:地铁线路
     @property (nonatomic) int epoitype;
     ///POI坐标
     @property (nonatomic) CLLocationCoordinate2D pt;
     ///是否有全景
     @property (nonatomic, assign) BOOL panoFlag;
     */
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableView.hidden = YES;
    
    BMKPoiInfo *poi = self.dataArr[indexPath.row];
    
//    //1、反向编码
//    BMKReverseGeoCodeOption *reverseGeocodeOption = [BMKReverseGeoCodeOption new];
//    reverseGeocodeOption.reverseGeoPoint = poi.pt;
//    [self.geoCodeSearch reverseGeoCode:reverseGeocodeOption]; //反向编码
    
    //2、正向编码
    BMKGeoCodeSearchOption *geoCodeOption = [BMKGeoCodeSearchOption new];
    geoCodeOption.city = poi.city;
    geoCodeOption.address = poi.address;
    [self.geoCodeSearch geoCode:geoCodeOption];
}

- (void)initSubControls{
    
    CGSize size = [UIScreen mainScreen].bounds.size;
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 60, 30)];
    backBtn.backgroundColor = [UIColor blackColor];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backLastPage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    //添加搜索按钮
    self.txtField = [[UITextField alloc] initWithFrame:CGRectMake(10, 75, size.width-90, 30)];
    self.txtField.layer.borderWidth = 1;
    self.txtField.layer.borderColor = [UIColor grayColor].CGColor;
    self.txtField.layer.masksToBounds = YES;
    self.txtField.layer.cornerRadius = 4;
    self.txtField.placeholder = @"输入搜索关键字";
    self.txtField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
    self.txtField.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.txtField];
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(size.width-70, 75, 60, 30)];
    searchBtn.backgroundColor = [UIColor grayColor];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(startSearch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textContentChange) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 300, size.width, size.height - 300)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.dataArr = [NSMutableArray new];
    
    //展示地址信息
    self.addressLbl = [[UILabel alloc] initWithFrame:CGRectMake(90, 30, size.width - 100, 30)];
    self.addressLbl.font = [UIFont systemFontOfSize:12];
    self.addressLbl.numberOfLines = 0;
    [self.view addSubview:self.addressLbl];
}

- (void)textContentChange{
    
    NSLog(@"%@", self.txtField.text);
}

- (void)dealloc{
    NSLog(@"....%@控制器被销毁。。。", [self class]);
}

- (void)backLastPage{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
